package NewTmas.EditMode;

import NewTmas.Graphs.GraphVizGraph;
import att.grappa.Node;

import taskmaster.auth.User;
import taskmaster.job.JobAllTasksCollection;
import taskmaster.job.Task;
import taskmaster.util.LookupLists;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: abhatnag
 * Date: 8/19/11
 * Time: 12:16 PM
 * To change this template use File | Settings | File Templates.
 */
public class EditTaskListener implements ActionListener
{
    String jobname;
    GraphVizGraph graphVizGraph;
    Connection connection;
    EditIntFrame editIntFrame;
    LookupLists ll;
    JobAllTasksCollection alltc;
    JComboBox typeCbox;
    JComboBox roleCbox;
    JTextField descField = new JTextField();
    JTextField commandField = new JTextField();
    JTextField retries = new JTextField();
    JTextField timeout = new JTextField();
    HashMap<String, String> rolesHash = new HashMap<String, String>();
    HashMap<String, String> typeHash = new HashMap<String, String>();
    JComboBox nodecbox;
    String TaskType;
    String TaskRole;


    public EditTaskListener(String job, GraphVizGraph graphVizGraph, User user, EditIntFrame editIntFrame, LookupLists ll, JobAllTasksCollection alltc)
    {
        this.jobname = job;
        this.graphVizGraph = graphVizGraph;
        this.connection = user.getConnection();
        this.editIntFrame = editIntFrame;
        this.ll = ll;
        this.alltc = alltc;
    }

    public void actionPerformed(ActionEvent e)
    {


        Node[] nodes = graphVizGraph.getGraph().nodeElementsAsArray();
        String[] currentNodeNames = new String[nodes.length];
        for (int i = 0; i < nodes.length; i++)
        {
            currentNodeNames[i] = nodes[i].getName();
        }

        Arrays.sort(currentNodeNames);
        nodecbox = new JComboBox(currentNodeNames);
        roleCbox = new JComboBox();
        typeCbox = new JComboBox();


        final AutoFillComboBoxesListener listener = new AutoFillComboBoxesListener();
        //populate initially too
        listener.actionPerformed(null);
        nodecbox.addActionListener(listener);

        Object message = new Object[]{"Task_tag", nodecbox, "Role", roleCbox, "Type", typeCbox, "Description", descField, "Command", commandField, "Retries", retries, "Timeout", timeout};

        int input = JOptionPane.showConfirmDialog(null, message, "Select a task to add", JOptionPane.OK_CANCEL_OPTION);

        if (input == JOptionPane.OK_OPTION)
        {

            String type = typeCbox.getSelectedItem().toString();
            String role = roleCbox.getSelectedItem().toString();

            for (Map.Entry<String, String> entry : typeHash.entrySet())
            {
                if (entry.getValue().equalsIgnoreCase(type))
                {
                    TaskType = entry.getKey();
                    break;
                }
            }

            for (Map.Entry<String, String> entry : rolesHash.entrySet())
            {
                if (entry.getValue().equalsIgnoreCase(role))
                {
                    TaskRole = entry.getKey();
                    break;
                }
            }

            editTaskcommand(jobname, descField.getText(), commandField.getText(), TaskType, TaskRole, retries.getText(), timeout.getText(), nodecbox.getSelectedItem().toString());
        }

    }

    private void editTaskcommand(String jobname, String descFieldText, String commandFieldText, String type, String role, String retriesText, String timeoutText, String taskTag)
    {
        String command = "update " +
                "(select role_id,type,description,command,retries,timeout from tms.tasks where job_tag='" + jobname + "'and task_tag='" + taskTag + "')" +
                " set role_id=" + Integer.valueOf(role) +
                ", type='" + type +
                "',description='" + descFieldText +
                "',command='" + commandFieldText +
                "',retries=" + Integer.valueOf(retriesText) +
                ",timeout=" + timeoutText;

        CallPreparedCommandSQL preparedCommandSQL = new CallPreparedCommandSQL(command, connection, graphVizGraph, jobname);

        editIntFrame.sqlCommands.add(preparedCommandSQL);
        editIntFrame.model.addElement(preparedCommandSQL.toString());
        editIntFrame.sqlcommandsList.setModel(editIntFrame.model);

    }

    private class AutoFillComboBoxesListener implements ActionListener
    {

        public void actionPerformed(ActionEvent e)
        {

            final String taskName = nodecbox.getSelectedItem().toString();
            Task editingTask = null;

            for (taskmaster.job.Task t : alltc.alljobTasks)
            {
                if (t.getTaskTag().equalsIgnoreCase(taskName))
                {
                    editingTask = t;
                    break;
                }

            }
            if (editingTask == null)
            {
                return;
            }

            typeHash.putAll(ll.getAllTypesHash());


            for (String o : typeHash.keySet())
            {
                typeCbox.addItem(typeHash.get(o));
                if (o.equalsIgnoreCase(Character.toString(editingTask.getType())))
                {
                    typeCbox.setSelectedItem(typeHash.get(o));
                }

            }

            rolesHash.putAll(ll.getAllRolesHash());

            for (String i : rolesHash.keySet())
            {
                roleCbox.addItem(rolesHash.get(i));
                if (i.equalsIgnoreCase(String.valueOf(editingTask.getRoleId())))
                {
                    roleCbox.setSelectedItem(rolesHash.get(i));
                }

            }

            descField.setText(editingTask.getDescription());
            commandField.setText(editingTask.getCommand());
            retries.setText(String.valueOf(editingTask.getRetries()));
            timeout.setText(String.valueOf(editingTask.getTimeout()));

        }
    }
}
